package com.conversationboard.model;

import java.sql.SQLException;
import java.util.Date;

import javax.mail.MessagingException;
import javax.naming.NamingException;

import com.conversationboard.email.Mail;

/**
 * To prevent users making use of automated tools to blast messages at the board. Every time a user posts a message, the time is recorded. If a user posts a
 * message again within say, 15 milliseconds of the last post, the counter is incremented. If the user posts a message in a time *greater* than the increment,
 * the count is set to 0 again. If the user posts greater than THRESHHOLD messages (say 100), all within 15 seconds of each other, the user is temporarily
 * banned and the admins are informed.
 * 
 * @author Keith Watson
 */

public class MessageFloodChecker {

	private static long INTERVAL_IN_MILLISECONDS = 30000;
	private static int THRESHHOLD = 50;


	public static void check(User user) throws SQLException, NamingException, MessagingException {

		Date now = new Date();

		if (user.getLastMessageTime() == null) {
			user.setLastMessageTime(now);
			return;
		}

		long differenceInMillseconds = (now.getTime() - user.getLastMessageTime().getTime());

		/* If the previous message was <= the interval, increment the counter. If it wasn't, reset the counter to 0. */

		if (differenceInMillseconds <= INTERVAL_IN_MILLISECONDS) {
			user.incrementMessageFloodCount();

			/*
			 * If we've breached the threshhold (i.e. x number of messages, all within the interval of each other, then ban the user temporarily and notify the
			 * site admins
			 */

			if (user.getMessageFloodCount() >= THRESHHOLD) {

				User systemUser = User.getSystemUser();
				user.ban(systemUser, "ILX System: user has flooded the board with messages.", true);

				String title = "Automated Message: Message Flooding Detected";
				String body = "User: " + user.getLoginId() + "/" + user.getDisplayName() + " has been caught flooding the board with messages. A temporary ban has been automatically instigated.";

				Mail mail = new Mail();
				mail.sendToSiteAdmins(title, body);

				user.setMessageFloodCount(0);
			}

		} else {
			user.setMessageFloodCount(0);
		}

		/* Update the time of the last message posted to be now */
		user.setLastMessageTime(now);

	}

}
